package cn.org.rookie.jeesdp.authentication.interceptor;

import cn.org.rookie.jeesdp.authentication.annotation.Permissions;
import cn.org.rookie.jeesdp.core.utils.SecurityUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class SecurityHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
        if (handler instanceof HandlerMethod handlerMethod) {
            Permissions permissions = handlerMethod.getMethodAnnotation(Permissions.class);
            if (permissions != null) {
                String role = permissions.hasRole();
                if (!"".equals(role)) {
                    return SecurityUtils.getAuthorities().contains("");
                }
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                return false;
            } else {
                return true;
            }
        }
        return true;
    }
}
